package com.bb.blog.mybatis.handler;

import org.apache.ibatis.type.*;
import org.springframework.util.StringUtils;

import java.sql.*;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;



@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes({List.class})
@Alias("VarcharToList")
public class VarcharToList extends BaseTypeHandler<List<String>> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<String> parameter, JdbcType jdbcType) throws SQLException {
        String value;
        if(parameter.isEmpty()){
            value = null;
        }else{
            value = String.join(",", parameter);
        };
        ps.setString(i,value);
    }

    @Override
    public List<String> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String value = rs.getString(columnName);
        if(StringUtils.isEmpty(value)){
            return Collections.emptyList();
        }
        return Arrays.asList(value.split(","));
    }

    @Override
    public List<String> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String value = rs.getString(columnIndex);
        if(StringUtils.isEmpty(value)){
            return Collections.emptyList();
        }
        return Arrays.asList(value.split(","));
    }

    @Override
    public List<String> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String value = cs.getString(columnIndex);
        if(StringUtils.isEmpty(value)){
            return Collections.emptyList();
        }
        return Arrays.asList(value.split(","));
    }
}
